# -*- conding:UTF-8 -*-

'''
@ Project: p7_flask
@ File: users.py
@ Author: 师路遥
@ Date：2022/6/6 13:32

'''
import redis,random
from datetime import datetime,timedelta
from flask import Blueprint,jsonify,g
from flask_restful import Api,Resource,reqparse,marshal
from models.user import *
from models import db
from werkzeug.security import generate_password_hash
# from common.send_sms_code import sms_code
from celery_tasks.tasks.task import sms_code
from common.utils.jwt_util import generate_token,check_token
from common.model_fields.user import user_fields,channel_fields
from common.utils.login_utils import login_required
from sqlalchemy import and_
from common.utils.user_cache import UserCache

user_bp = Blueprint('user_bp',__name__,url_prefix='/users')

api = Api(user_bp)

class UserRegister(Resource):
    """注册"""
    def post(self):
        parse = reqparse.RequestParser()
        parse.add_argument('username')
        parse.add_argument('password')
        parse.add_argument('nickname')
        parse.add_argument('mobile')
        parse.add_argument('comfirmpassword')
        args = parse.parse_args()
        username = args.get('username')
        password = args.get('password')
        nickname = args.get('nickname')
        mobile = args.get('mobile')
        comfirmpassword = args.get('comfirmpassword')

        if len(username) > 32:
            return jsonify(message='账号过长',code=400)
        if password != comfirmpassword:
            return jsonify(message='两次密码不一致',code=400)
        user_num = UserModel.query.filter_by(mobile=mobile).count()
        if user_num >=1:
            return jsonify(message='手机号已经存在',code=400)

        hash_pwd = generate_password_hash(password)
        try:
            user = UserModel(account=username,password=hash_pwd,mobile=mobile,uname=nickname)
            db.session.add(user)
            db.session.commit()
            return jsonify(message='注册成功',code=200)
        except Exception as e:
            print(e)
            return jsonify(message='注册失败',code=500)

class SendSMSCode(Resource):
    """发送短信验证码"""
    def post(self):
        params = reqparse.RequestParser()
        params.add_argument('mobile')
        args = params.parse_args()
        mobile = args.get('mobile')
        code = random.randint(10000,99999)
        print('1111111>>>>>>>>',code)
        rest = sms_code.delay(mobile,code)
        # if json.loads(rest)['statusCode'] == '000000':
        if rest:
            rds = redis.Redis(password='123456',db=2)
            rds.set('sms_%s'%mobile,code,ex=1000)
            return jsonify(message='短信验证码发送成功',code=200,code_=code)
        else:
            return jsonify(message='短信验证码发送失败',code=500)

class UserLogin(Resource):
    """登录"""
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('mobile')
        parser.add_argument('sms')
        args = parser.parse_args()
        mobile = args.get('mobile')
        sms_code = args.get('sms')
        print('>>>>>>>>>>>',mobile,sms_code)
        if not all([mobile, sms_code]):
            return jsonify(message='登录信息不完整', code=400)
        rds = redis.Redis(password='123456',db=2)
        origin_sms_code = rds.get("sms_%s" % mobile)

        if not origin_sms_code:
            return jsonify(message='验证码已过期', code=500)
        if sms_code != origin_sms_code.decode('utf-8'):
            return jsonify(message='验证码错误', code=400)
        # 登录成功,生成token
        try:
            user = UserModel.query.filter_by(mobile=mobile).first()

            print('user>>', user.account)
            data = {
                'user': user.account,
                'id': user.uid
            }
            expiry = timedelta(hours=2)  # 有效期
            token = generate_token(data, str(expiry))
            print('token>>', token)
            if token:
                data_ = {
                    'user_id': user.uid,
                    'token': token,
                    'refresh_token': ''
                }
                return jsonify(message='登录成功', code=200, data=data_)
            else:
                return jsonify(message='token生成失败', code=500)

        except Exception as e:
            print('获取用户错误', e)
            return jsonify(message='此手机号未注册', code=400)

class UserInfo(Resource):
    def get(self, id):
        """根据用户id 获取用户信息"""
        # user = UserModel.query.filter_by(uid=id).first()
        user = UserCache(id).get()
        print('>>>>>>>>>>>>>>',user)
        print(type(user))
        # if user:
        #     user = marshal(user, user_fields)
        return user

class UserChannelResource(Resource):
    @login_required
    def get(self):
        """
        获取用户关注的频道
        1.用户必须先登录
        2.根据登录的用户ID，查询关注的频道
        """
        uid = g.user_id
        if uid:
            user = UserModel.query.filter_by(uid=uid).first()
            # 根据登录的用户ID,查询关注的频道
            print('>>>>>>>>>>>',user.channels)
            # envelope='data'
            channels = marshal(user.channels,channel_fields)
            return channels

class CancelUserChannelResource(Resource):
    @login_required
    def get(self,id):
        uid = g.user_id
        if uid:
            user = UserModel.query.filter_by(uid=uid).first()
            UserChannel.query.filter(and_(UserChannel.uid==user.uid,UserChannel.cid==id)).delete()
            db.session.commit()

        return jsonify(message='取消关注成功',code=200)


api.add_resource(CancelUserChannelResource,'/user_channels/<int:id>')
api.add_resource(UserChannelResource,'/channels')
api.add_resource(UserInfo,'/info/<int:id>')
api.add_resource(UserLogin,'/login')
api.add_resource(SendSMSCode,'/send_sms_code')
api.add_resource(UserRegister,'/register')
